<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!--contain-->
    <el-card>
      <!--add-->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!--table-->
      <el-table
        :data="categoriesTable"
        stripe
        border
        style="width: 100%"
        row-key="cat_id"
        :header-cell-style="{background:'#f8f8f9'}"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column prop="cat_deleted" label="是否有效">
          <template v-slot:default="scope">
            <i
              class="el-icon-success"
              v-if="scope.row.cat_deleted==false"
              style="color: rgb(32, 178, 170);"
            ></i>
            <i class="el-icon-error" v-else style="color: red;"></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序">
          <template v-slot:default="scope">
            <el-tag v-if="scope.row.cat_level==0">一级</el-tag>
            <el-tag v-else-if="scope.row.cat_level==1" type="success">二级</el-tag>
            <el-tag v-else type="warning">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditCateDialog(scope.row.cat_id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="delCategories(scope.row.cat_id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="categoriesSizeChange"
        @current-change="categoriesCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!--添加分类-->
    <el-dialog title="添加分类" :visible.sync="addCategoriesVisible" width="50%" @closed="resetAddForm">
      <el-form
        ref="addCategoriesRef"
        :model="addCategoriesForm"
        :rules="addCategoriesRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCategoriesForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="CascaderChange"
            size="medium"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoriesVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitAddCategories">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑分类-->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCategoriesVisible"
      width="50%"
      @closed="resetEditForm"
    >
      <el-form
        ref="editCategoriesRef"
        :model="editCategoriesForm"
        :rules="editCategoriesRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCategoriesForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoriesVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitEditCategories">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取表格数据
      categoriesTable: [],
      // 总条数
      total: 0,
      // 请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 10
      },
      // 添加商品类型
      addCategoriesVisible: false,
      // 添加商品分类
      addCategoriesForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      addCategoriesRules: {
        cat_name: [
          { required: true, message: '请输入商品分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '名称长度在1到20之间', trigger: 'blur' }
        ]
      },
      selectedKeys: {},
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover'
      },
      // 父级分类列表,不包含三级分类
      parentCateList: [],
      // 编辑分类
      editCategoriesVisible: false,
      editCategoriesForm: {
        cat_id: null,
        cat_name: ''
      },
      editCategoriesRules: {
        cat_name: [
          { required: true, message: '请输入商品分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '名称长度在1到20之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    // 获取商品分类列表
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败！')
      this.total = res.data.total
      this.categoriesTable = res.data.result
    },
    categoriesSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCategoriesList()
    },
    categoriesCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCategoriesList()
    },
    // 显示添加分类对话框
    showAddCateDialog() {
      this.selectedKeys = []
      this.addCategoriesVisible = true
      this.getParentCateList()
    },
    // 提交添加商品信息
    commitAddCategories() {
      this.$refs.addCategoriesRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('categories', this.addCategoriesForm)
        if (res.meta.status !== 201) return this.$message.error('添加分类失败！')
        this.$message.success('添加分类成功！')
        this.getCategoriesList()
        this.addCategoriesVisible = false
      })
    },
    resetAddForm() {
      this.$refs.addCategoriesRef.resetFields()
    },
    // 获取父级分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败！')
      this.parentCateList = res.data
    },
    // 监听cascader变化
    CascaderChange() {
      if (this.selectedKeys.length === 0) {
        this.addCategoriesForm.cat_level = 0
        this.addCategoriesForm.cat_pid = 0
      } else {
        this.addCategoriesForm.cat_level = this.selectedKeys.length
        this.addCategoriesForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
      }
    },
    // 显示编辑商品对话框
    async showEditCateDialog(id) {
      this.editCategoriesVisible = true
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error('商品信息获取失败！')
      this.editCategoriesForm.cat_name = res.data.cat_name
      this.editCategoriesForm.cat_id = res.data.cat_id
    },
    // 提交编辑商品信息
    commitEditCategories() {
      this.$refs.editCategoriesRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`categories/${this.editCategoriesForm.cat_id}`, this.editCategoriesForm)
        if (res.meta.status !== 200) return this.$message.error('编辑分类失败！')
        this.getCategoriesList()
        this.editCategoriesVisible = false
      })
    },
    resetEditForm() {
      this.$refs.editCategoriesRef.resetFields()
    },
    async delCategories(id) {
      await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败！')
        this.$message.success('删除成功！')
        this.getCategoriesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>
